package com.gec.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gec.common.CustomException;
import com.gec.dto.DishDto;
import com.gec.entity.Category;
import com.gec.entity.Dish;
import com.gec.entity.DishFlavor;
import com.gec.mapper.DishMapper;
import com.gec.service.CategoryService;
import com.gec.service.DishFlavorService;
import com.gec.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author : [chenxys]
 * @version : [v1.0]
 * @createTime : [2022/7/9 13:56]
 */
@Slf4j
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品并保存相应的口味数据
     * @author chenxys
     * @param dishDto 菜品信息
     * 多张表 --> 开启事务
     * @return void
     */
    @Transactional
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        // 保存基础数据到dish表
        this.save(dishDto);
        // 获取菜品编号
        Long dishId = dishDto.getId();
        // 获取口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        // item代表一个DishFlavor   .collect(Collectors.toList()); 变成集合
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        // 保存到菜品口味表
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        // 查询菜品信息
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        // 将Dish复制到DishDto中
        BeanUtils.copyProperties(dish,dishDto);
        // 查询当前菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> flavorList = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavorList);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateBatchByIds(Integer code, Long[] ids) {
        List<Dish> dishList = new ArrayList<>();
        Dish dish = null;
        for (Long id : ids) {
            dish = new Dish();
            dish.setId(id);
            dish.setStatus(code);
            dishList.add(dish);
        }
        this.updateBatchById(dishList);
    }

    @Override
    @Transactional
    public void updateByDishDto(DishDto dishDto) {
        List<DishFlavor> flavors = dishDto.getFlavors();
        this.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        // 删除原有关系
        dishFlavorService.remove(queryWrapper);
        // 新建关系
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        // 从新插入数据库
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    @Transactional
    public void removeByIdsWithFlavor(List<Long> ids) {
        // 查询菜品状态
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 构造条件
        queryWrapper.in(Dish::getId,ids);
        // 在售状态
        queryWrapper.eq(Dish::getStatus,1);
        // 查询
        int count = this.count(queryWrapper);
        if (count > 0){
            // 当前选中的菜品正在售卖
            throw new CustomException("当前选中的菜品正在售卖");
        }
        // 可以删除
        this.removeByIds(ids);
        // 构造口味条件
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构造条件
        dishFlavorLambdaQueryWrapper.in(DishFlavor::getDishId,ids);
        // 删除
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
    }

    @Override
    public IPage<DishDto> pages(IPage<Dish> pageInfo, String name) {
        Page<DishDto> dishDtoPage = new Page<>();
        // 构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        // 构造排序条件
        queryWrapper.orderByAsc(Dish::getSort);

        // 分页查询
        this.page(pageInfo,queryWrapper);
        // 拷贝到dto              源文件     目标文件                     忽略的属性
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        // 获取数据
        List<Dish> dishList = pageInfo.getRecords();
        List<DishDto> dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            // 将dish 复制到 dishdto
            BeanUtils.copyProperties(item,dishDto);
            // 获取分类ID
            Long categoryId = dishDto.getCategoryId();
            Category category = categoryService.getById(categoryId);
            // 避免空指针
            if (!ObjectUtils.isEmpty(category)){
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoList);
        return dishDtoPage;
    }

    @Override
    public List<DishDto> listByDish(Dish dish) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 构造查询条件
        queryWrapper.eq(!ObjectUtils.isEmpty(dish.getCategoryId()),Dish::getCategoryId,dish.getCategoryId());
        // 添加条件,查询状态为1(启售)的菜
        queryWrapper.eq(Dish::getStatus,1);
        // 排序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        // 查询
        List<Dish> dishList = this.list(queryWrapper);

        //
        List<DishDto> dishDtoList = null;
        dishDtoList = dishList.stream().map((item) -> {
                    DishDto dishDto = new DishDto();
                    BeanUtils.copyProperties(item,dishDto);
                    // 分类ID
                    Long categoryId = item.getCategoryId();
                    // 根据ID查询分类对象
                    Category category = categoryService.getById(categoryId);
                    if (!ObjectUtils.isEmpty(category)){
                        dishDto.setCategoryName(category.getName());
                    }
                    // 当前菜品ID
                    Long dishId = item.getId();
                    // 当前菜品的口味
                    LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    // 封装查询条件
                    dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
                    // 查询
                    List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
                    // 设置菜品口味
                    dishDto.setFlavors(dishFlavorList);
                    // 返回当前菜品
                    return dishDto;
                })
                .collect(Collectors.toList());

        return dishDtoList;
    }
}
